package com.wenzhoujie;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.wenzhoujie.library.customview.ClearEditText;
import com.wenzhoujie.library.customview.SDSendValidateButton;
import com.wenzhoujie.library.customview.SDSendValidateButton.SDSendValidateButtonListener;
import com.wenzhoujie.library.dialog.SDDialogConfirm;
import com.wenzhoujie.library.dialog.SDDialogCustom;
import com.wenzhoujie.library.dialog.SDDialogCustom.SDDialogCustomListener;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDToast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.adapter.ShopCartAdapter;
import com.wenzhoujie.adapter.ShopCartAdaptertest;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.customview.SDListViewInScroll;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.fragment.LoginPhoneFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.CartGoodsArrayList;
import com.wenzhoujie.model.CartGoodsModel;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.PostCartActModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.ShopGoodsModel;
import com.wenzhoujie.model.act.BaseActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * 购物车
 * 
 * @author js02
 * 
 */
public class ShopCartActivity extends BaseActivity implements OnClickListener {
	public static final int REQUEST_CODE_REQUEST_LOGIN = 1;
	public static final int REQUEST_CODE_REQUEST_BIND_PHONE = 2;

	@ViewInject(id = R.id.act_shop_cart_ptrsv_all)
	private PullToRefreshScrollView mPtrsvAll = null;

	@ViewInject(id = R.id.act_shop_cart_lv_cart_goods)
	private SDListViewInScroll mLvCartGoods = null;

	@ViewInject(id = R.id.act_shop_cart_rl_empty)
	private RelativeLayout mRlEmpty = null;

	@ViewInject(id = R.id.act_shop_cart_iv_empty)
	private ImageView mIvEmpty = null;

	@ViewInject(id = R.id.act_shop_cart_tv_empty)
	private TextView mTvEmpty = null;
	/** 绑定手机号码布局 */
	@ViewInject(id = R.id.act_shop_cart_ll_bind_phone)
	private LinearLayout mLlBindPhone = null;
	/** 绑定手机号码可点击区域布局 */
	@ViewInject(id = R.id.act_shop_cart_ll_bind_phone_click)
	private LinearLayout mLlBindPhoneClick = null;

	@ViewInject(id = R.id.act_shop_cart_tv_bind_phone_label)
	private TextView mTvBindPhoneLabel = null;

	@ViewInject(id = R.id.act_shop_cart_tv_bind_phone_tip)
	private TextView mTvBindPhoneTip = null;

	@ViewInject(id = R.id.act_shop_cart_tv_binded_phone)
	private TextView mTvBindedPhone = null;
	/** 手机登录布局 */
	@ViewInject(id = R.id.act_shop_cart_ll_phone_login)
	private LinearLayout mLlPhoneLogin = null;
	/** 手机登录输入手机号的输入框 */
	@ViewInject(id = R.id.act_shop_cart_et_phone_login_number)
	private ClearEditText mEtPhoneLoginNumber = null;
	/** 验证码输入框 */
	@ViewInject(id = R.id.act_shop_cart_et_code)
	private ClearEditText mEtValidateCode = null;
	/** 发送验证码按钮 */
	@ViewInject(id = R.id.act_shop_cart_btn_sand_validate)
	private SDSendValidateButton mBtnSendValidateCode = null;

	@ViewInject(id = R.id.act_shop_cart_tv_unlogin_buy)
	private TextView mTvUnLoginBuy = null;

	private List<CartGoodsModel> mListModel = new ArrayList<CartGoodsModel>();

	private ShopCartAdapter mAdapter = null;

	private String mStrPhoneLoginNumber = null;
	private String mStrValidateCode = null;

	private PostCartActModel mModel = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.act_shop_cart);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init() {
		initTitle();
		bindDefaultData();
		registeClick();
		registeValidateCodeEdittextChangeListener();
		initViewState();
		initSDSendValidateButton();
		initPullToRefreshScrollView();
	}

	private void initPullToRefreshScrollView() {
		mPtrsvAll.setMode(Mode.PULL_FROM_START);
		mPtrsvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				requestPostCartInterface();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
			}
		});
		mPtrsvAll.setRefreshing();
	}

	/**
	 * 验证码输入框字符变化监听
	 */
	private void registeValidateCodeEdittextChangeListener() {
		mEtValidateCode.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				mStrValidateCode = s.toString();
				initTitleRightButton(TextUtils.isEmpty(mStrValidateCode));
			}
		});

	}

	/**
	 * 初始化发送验证码按钮
	 */
	private void initSDSendValidateButton() {
		mBtnSendValidateCode
				.setmBackgroundEnableResId(R.drawable.layer_main_color_normal);
		mBtnSendValidateCode
				.setmBackgroundDisableResId(R.drawable.layer_main_color_press);
		mBtnSendValidateCode.setmListener(new SDSendValidateButtonListener() {
			@Override
			public void onTick() {
			}

			@Override
			public void onClickSendValidateButton() {
				String strPhoneLogin = mEtPhoneLoginNumber.getText().toString();
				if (TextUtils.isEmpty(strPhoneLogin)) {
					SDToast.showToast("请输入手机号码");
					mEtPhoneLoginNumber.requestFocus();
					return;
				}
				if (strPhoneLogin.length() != 11) {
					SDToast.showToast("请输入11位的手机号码");
					mEtPhoneLoginNumber.requestFocus();
					return;
				}
				mStrPhoneLoginNumber = strPhoneLogin;
				requestValidateCode();
			}
		});
	}

	/**
	 * 请求验证码
	 */
	protected void requestValidateCode() {
		RequestModel model = new RequestModel();
		model.put("act", "register_verify_phone");
		model.put("mobile", mStrPhoneLoginNumber);
		// is_login 0:仅注册,会判断手机号码,是否存在; 1:可登陆,可注册 不判断手机号码是否存在;
		model.put("is_login", 0);
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				BaseActModel model = JsonUtil.json2Object(responseInfo.result,
						BaseActModel.class);
				if (!SDInterfaceUtil.isActModelNull(model)) {
					int status = SDTypeParseUtil.getIntFromString(
							model.getStatus(), -1);
					switch (status) {
					case 0:

						break;
					case 1:
						mBtnSendValidateCode.startTickWork();
						break;
					case 2:
						showPhoneHasBindDialog();
						break;

					default:
						break;
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {
				AppHelper.hideLoadingDialog();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	private void showPhoneHasBindDialog() {
		new SDDialogConfirm()
				.setTextContent(
						mEtPhoneLoginNumber.getText().toString().trim()
								+ "已经被绑定是否直接用该手机号登录?")
				.setmListener(new SDDialogCustomListener() {

					@Override
					public void onDismiss(DialogInterface iDialog,
							SDDialogCustom dialog) {
					}

					@Override
					public void onClickConfirm(View v, SDDialogCustom dialog) {
						Intent intent = new Intent(ShopCartActivity.this,
								LoginNewActivity.class);
						intent.putExtra(
								LoginNewActivity.EXTRA_SELECT_TAG_INDEX, 1);
						intent.putExtra(LoginPhoneFragment.EXTRA_PHONE_NUMBER,
								mEtPhoneLoginNumber.getText().toString().trim());
						startActivity(intent);
					}

					@Override
					public void onClickCancel(View v, SDDialogCustom dialog) {
					}
				}).show();
	}

	private void initViewState() {
		if (AppHelper.isLogin()) {
			mLlPhoneLogin.setVisibility(View.GONE);
			mLlBindPhone.setVisibility(View.VISIBLE);
		} else {
			mLlPhoneLogin.setVisibility(View.VISIBLE);
			mLlBindPhone.setVisibility(View.GONE);
		}
	}

	private void registeClick() {
		mLlBindPhoneClick.setOnClickListener(this);
		mTvUnLoginBuy.setOnClickListener(this);
	}

	private void bindDefaultData() {
		
		if (App.getApplication().getListCartGoodsModel() != null) {
			mListModel = App.getApplication().getListCartGoodsModel();
		}
		/*user = App.getApplication().getmLocalUser();
		if(user!=null)
		getShopCart();*/
		mAdapter = new ShopCartAdapter(mListModel, this);
		mLvCartGoods.setAdapter(mAdapter);
	}

	private void initTitle() {
		mTitleSimple.setmListener(new SDTitleSimpleListener() {

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v) {
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v) {
				finish();
			}
		});
		mTitleSimple.setTitleTop("购物车");

		initTitleRightButton(AppHelper.isLogin());

	}

	/**
	 * 设置标题栏右边按钮状态
	 * 
	 * @param isLogin
	 */
	private void initTitleRightButton(boolean isLogin) {
		if (!isLogin) {
			mTitleSimple.setRightText("登录");
			mTitleSimple.setRightLayoutClick(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					startActivityForResult(new Intent(getApplicationContext(),
							LoginNewActivity.class), REQUEST_CODE_REQUEST_LOGIN);
				}
			});
		} else {
			if (mModel != null) {
				int isForceBind = SDTypeParseUtil.getIntFromString(
						mModel.getOrder_has_bind_mobile(), 0);
				if (isForceBind == 1) {
					int isBind = SDTypeParseUtil.getIntFromString(
							mModel.getIs_binding(), 0);
					if (isBind == 1) {
						mTitleSimple.setRightText("去结算");
						mTitleSimple.setRightLayoutClick(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								clickSettleAccounts();
							}
						});
					} else {
						SDToast.showToast("绑定手机号后才能购买");
						mTitleSimple.setRightText("");
					}
				} else {
					mTitleSimple.setRightText("去结算");
					mTitleSimple.setRightLayoutClick(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							clickSettleAccounts();
						}
					});
				}
			} else {
				mTitleSimple.setRightText("");
			}
		}
	}

	/**
	 * 去结算
	 */
	private void clickSettleAccounts() {
		if (mLlPhoneLogin.getVisibility() == View.VISIBLE) {
			if (TextUtils.isEmpty(mStrPhoneLoginNumber)) {
				SDToast.showToast("您还未获取验证码进行手机登陆");
				mEtPhoneLoginNumber.requestFocus();
				return;
			}
			if (TextUtils.isEmpty(mStrValidateCode)) {
				SDToast.showToast("您还未输入验证码");
				mEtValidateCode.requestFocus();
				return;
			}
		}

		if (mListModel.size() <= 0) {
			SDToast.showToast("您的购物车中没有商品");
		} else {
			Intent intent = new Intent(getApplicationContext(),
					ConfirmOrderActivity.class);
			intent.putExtra(ConfirmOrderActivity.EXTRA_LIST_CART_GOODS_MODEL,
					(App.getApplication().getListCartGoodsModel()));
			intent.putExtra(ConfirmOrderActivity.EXTRA_PHONE_LOGIN_NUMBER,
					mStrPhoneLoginNumber);
			intent.putExtra(
					ConfirmOrderActivity.EXTRA_PHONE_LOGIN_VALIDTE_CODE,
					mStrValidateCode);

//			App.getApplication().setShopModelList(mListModel);
			startActivity(intent);
		}
	}

	private void requestPostCartInterface() {

		RequestModel model = new RequestModel();
		model.put("act", "postcart");
		model.putUser();
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {
				AppHelper.showLoadingDialog("请稍候");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				PostCartActModel actModel = JsonUtil.json2Object(
						responseInfo.result, PostCartActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel)) {
					mModel = actModel;
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {
				mPtrsvAll.onRefreshComplete();
				AppHelper.hideLoadingDialog();
				changeViewStateByRequestResult(mModel);
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	/**
	 * 
	 * 根据请求结果改变view状态
	 * 
	 */
	protected void changeViewStateByRequestResult(PostCartActModel model) {
		initTitle();
		initViewState();
		if (model != null) {
			int isBind = SDTypeParseUtil.getIntFromString(
					model.getIs_binding(), 0);
			switch (isBind) {
			case 1: // 已经有绑定手机号码
				mTvBindPhoneLabel.setText("您绑定的手机号码");
				mTvBindPhoneTip.setText("绑定新号码");
				String mobile = model.getMobile();
				if (!TextUtils.isEmpty(mobile)) {
					mTvBindedPhone.setText(mobile);
				}
				break;
			default:
				mTvBindPhoneLabel.setText("您还未绑定手机号码");
				mTvBindPhoneTip.setText("绑定手机号码");
				break;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CODE_REQUEST_BIND_PHONE:
			if (resultCode == BindPhoneActivity.RESULT_CODE_BIND_PHONE_SUCCESS) // 绑定手机号成功
			{
				mPtrsvAll.setRefreshing();
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.act_shop_cart_ll_bind_phone_click:
			clickBindPhone();
			break;
		case R.id.act_shop_cart_tv_unlogin_buy:
			clickSettleAccounts();
			break;

		default:
			break;
		}

	}

	private void clickBindPhone() {
		// TODO 跳到绑定手机界面
		Intent intent = new Intent(getApplicationContext(),
				BindPhoneActivity.class);
		startActivityForResult(intent, REQUEST_CODE_REQUEST_BIND_PHONE);
	}

	@Override
	public void onEventMainThread(SDBaseEvent event) {
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		switch (EnumEventTag.valueOf(event.getEventTagInt())) {
		case DONE_CART_SUCCESS:
			finish();
			break;
		case LOGIN_NORMAL_SUCCESS:
			initTitle();
			initViewState();
			mPtrsvAll.setRefreshing();
			break;

		default:
			break;
		}
	}

	// 获取购物车列表
	LocalUserModel user = null;

	private void getShopCart() {
		
		RequestModel model = new RequestModel();
		model.put("act", "cart");
		model.put("a", "get");
		model.put("email", user.getUser_name());
		model.put("pwd", user.getUser_pwd());
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				mListModel.clear();
				JSONObject json = JSON.parseObject(responseInfo.result);
				org.json.JSONObject jsonresponse_code;
				try {
					jsonresponse_code = new org.json.JSONObject(
							json.getString("response_code"));
					Gson gson = new Gson();
					List<ShopGoodsModel> listModel = gson.fromJson(
							jsonresponse_code.getString("cart_list"),
							new TypeToken<List<ShopGoodsModel>>() {
							}.getType());
					
					/*
					 * for (int i = 0; i < listModel.size(); i++) {
					 * App.getApplication().getListCartGoodsModel()
					 * .add(getCartGoodsArrayList(listModel.get(i))); }
					 */
//					mListModel.addAll(listModel);
					mAdapter.notifyDataSetChanged();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {

			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	/*
	 * public CartGoodsModel getCartGoodsArrayList(ShopGoodsModel listModel) {
	 * CartGoodsModel cartGoodsModel = new CartGoodsModel();
	 * cartGoodsModel.setAttr_id_1(attr_id_1);
	 * cartGoodsModel.setAttr_id_2(attr_id_2);
	 * cartGoodsModel.setAttr_id_a(attr_id_a);
	 * cartGoodsModel.setAttr_id_b(attr_id_b);
	 * cartGoodsModel.setAttr_title_a(attr_title_a);
	 * cartGoodsModel.setAttr_title_b(attr_title_b);
	 * cartGoodsModel.setAttr_value_a(attr_value_a);
	 * cartGoodsModel.setAttr_value_b(attr_value_b);
	 * cartGoodsModel.setCart_id(cart_id); cartGoodsModel.setGoods(null,
	 * validate); cartGoodsModel.setGoods_id(goods_id);
	 * cartGoodsModel.setHas_attr(has_attr);
	 * cartGoodsModel.setHas_attr_1(has_attr_1);
	 * cartGoodsModel.setHas_cart(has_cart); cartGoodsModel.setLimit_num(null);
	 * cartGoodsModel.setLimit_num_format_int(0);
	 * cartGoodsModel.setScore(listModel.getReturn_score());
	 * cartGoodsModel.setTotal(listModel.getReturn_total_money());
	 * cartGoodsModel.setTotal_format_string(listModel.getReturn_total_money());
	 * return cartGoodsModel; }
	 */
}